package com.durian.base.rxhttp.parse

import com.google.gson.*
import java.lang.reflect.Type

/**
 * 说明：GsonConvert
 * <p/>
 * 作者：Fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2020/04/25 19:44
 * <p/>
 * 版本：version 1.0
 */
object GsonConverter{

    val gson: Gson by lazy {
        GsonBuilder().disableHtmlEscaping()
                .registerTypeAdapter(String::class.java, GsonStringAdapter())
//                .registerTypeAdapter(Int.javaClass, GsonIntAdapter())
//                .registerTypeAdapter(Double.javaClass, GsonDoubleAdapter())
//                .registerTypeAdapter(Long.javaClass, GsonLongAdapter())
                .create()
    }

    fun <T> convert(result:String, type: Type): T {
        return gson.fromJson(result,type)
    }

}

internal class GsonStringAdapter : JsonSerializer<String>, JsonDeserializer<String> {
    override fun serialize(src: String?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
        return JsonPrimitive(src)
    }

    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): String {
        return if (json is JsonPrimitive) {
            json.asString
        } else {
            json.toString()
        }
    }

}

//internal class GsonIntAdapter : JsonSerializer<Int>, JsonDeserializer<Int> {
//    override fun serialize(src: Int?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
//        return JsonPrimitive(src)
//    }
//
//    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Int {
//        return if (json?.asString.isNullOrEmpty()) {
//            0
//        } else {
//            json?.asInt ?: 0
//        }
//    }
//
//}

//internal class GsonDoubleAdapter : JsonSerializer<Double>, JsonDeserializer<Double> {
//    override fun serialize(src: Double?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
//        return JsonPrimitive(src)
//    }
//
//    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Double {
//        return if (json?.asString.isNullOrEmpty()) {
//            0.0
//        } else {
//            json?.asDouble ?: 0.0
//        }
//    }
//
//}

//internal class GsonLongAdapter : JsonSerializer<Long>, JsonDeserializer<Long> {
//    override fun serialize(src: Long?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
//        return JsonPrimitive(src)
//    }
//
//    override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Long {
//        return if (json?.asString.isNullOrEmpty()) {
//            0L
//        } else {
//            json?.asLong ?: 0L
//        }
//    }
//
//}